package com.leyou.service.impl;

import com.leyou.client.UserClient;
import com.leyou.config.JwtProperties;
import com.leyou.pojo.User;
import com.leyou.pojo.UserInfo;
import com.leyou.service.AuthService;
import com.leyou.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthServiceImpl implements AuthService {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserClient userClient;

    private Logger logger = LoggerFactory.getLogger(AuthServiceImpl.class);

    @Override
    public String accredit(String username, String password) {

        UserInfo userInfo = new UserInfo();
        //跨服调用user-service服务,查询出user
        try {
            User user = userClient.queryUser(username, password);
            BeanUtils.copyProperties(user, userInfo);
            if (null == user) {
                logger.info("该用户不存在,username{}", username);
                return null;
            }
            //生成token
            String token = JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            if (token != null) {
                return token;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
